<template>
  <nw-PageTitle
    isBack
    isFixed
    :isStatusBar="true"
    statusBarBgColor="transparent"
    backgroundColor="transparent"
    leftIconColor="#fff"
  />
  <nw-PageContainer :isTitle="false">
    <view class="bg-img">
      <image
        :src="deviceSumInfo.recipeInfo?.picturePath"
        mode="aspectFit"
        class="recipe-img"
      />
      <view class="recipe-title">{{ deviceSumInfo.recipeInfo?.name }}</view>
    </view>
    <view class="content">
      <view class="device-title">
        {{ deviceSumInfo.deviceInfo?.name }}：{{
          g_options.getOptionText(
            g_options.deviceStatusOptions,
            deviceSumInfo.deviceInfo?.status,
            '--'
          )
        }}
         <warning-modal-icon
                  :deviceSn="deviceSumInfo.deviceInfo?.sn"
                  />
      </view>
      <view class="charts-wrap">
        <view class="charts-box">
          <progressBarChart
            :value="deviceSumInfo.currentWorkTemperatureProgress"
            :title="`${deviceSumInfo.deviceInfo.currentWorkTemperature}°C`"
            subTitle="温度"
          />
        </view>
        <view class="charts-box">
          <progressBarChart
            :value="deviceSumInfo.currentWorkPowerLevelProgress"
            :title="`${deviceSumInfo.deviceInfo.currentWorkPowerLevel}档`"
            subTitle="功率"
          />
        </view>
        <view class="charts-box">
          <progressBarChart
            :value="deviceSumInfo.progress"
            :title="deviceSumInfo.remainSecondsText"
            subTitle="剩余"
          />
        </view>
      </view>
      <view class="progress-title">炒菜进度</view>
      <scroll-view class="scroll-content" scroll-y>
        <view class="lists">
          <view
            :class="['list']"
            v-for="(row, i) in deviceSumInfo.recipeInfo.stepList"
            :key="row"
          >
            <view
              :class="[
                'dot',
                {
                  active: i === stepIndex
                }
              ]"
            ></view>
            <view class="step-box">
              <view
                :class="[
                  'step-content',
                  {
                    completed: i < stepIndex,
                    active: i === stepIndex,
                    unactive: i > stepIndex
                  }
                ]"
                :style="
                  stepIndex === i
                    ? {
                        background: `linear-gradient(to right, ${bgColor} ${bgWidth}%, transparent 0)`
                      }
                    : {}
                "
              >
                <view class="step">
                  步骤{{ i + 1 }}/{{
                    deviceSumInfo.recipeInfo.stepList.length
                  }}：{{ row.name }}
                </view>
                <view class="duration">
                  {{ getStepStatusText(i) }}
                  {{ deviceSumInfo.recipeInfo.stepList[i].timeOffset }}s
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="btns">
      <nw-Button
        v-if="deviceSumInfo.deviceInfo?.status === deviceStatus.Idle"
        text="关机"
        @click="handleShutdown"
      ></nw-Button>
      <nw-Button
        v-if="deviceSumInfo.deviceInfo?.status === deviceStatus.Idle"
        text="自动洗锅"
        @click="handleAutoWashPot"
      ></nw-Button>
      <nw-Button
        v-if="deviceSumInfo.deviceInfo?.status === deviceStatus.Idle"
        text="手动洗锅"
        @click="handleManualWashPot"
      ></nw-Button>
      <nw-Button
        v-if="deviceSumInfo.deviceInfo?.status === deviceStatus.ManualWashPot"
        text="完成洗锅"
        @click="handleCompleteWashPot(row)"
      ></nw-Button>
      <nw-Button
        v-if="deviceSumInfo.deviceInfo?.status == deviceStatus.Cooking"
        text="暂停"
        @click="handlePause"
      ></nw-Button>
      <nw-Button
        v-if="deviceSumInfo.deviceInfo?.status == deviceStatus.Pause"
        text="继续"
        @click="handleContinue"
      ></nw-Button>
      <nw-Button
        v-if="
          deviceSumInfo.deviceInfo?.status === deviceStatus.Cooking ||
          deviceSumInfo.deviceInfo?.status === deviceStatus.Pause
        "
        text="终止"
        @click="handleStop"
      ></nw-Button>
      <nw-Button
        v-if="deviceSumInfo.deviceInfo?.status === deviceStatus.WaitPlating"
        text="开始出菜"
        @click="handleOutPot"
      ></nw-Button>
      <nw-Button
        v-if="deviceSumInfo.deviceInfo?.status === deviceStatus.InPlating"
        text="完成出菜"
        @click="handleCompleteOutPot"
      ></nw-Button>
    </view>
  </nw-PageContainer>
  <up-toast ref="uToastRef" />
</template>

<script setup>
import progressBarChart from './component/progressBarChart.vue'
import WarningModalIcon from './component/WarningModalIcon/index.vue'
import { deviceProtocolRecipeService } from '@/service/deviceProtocolRecipeService.js'
import { deviceProtocolManualService } from '@/service/deviceProtocolManualService.js'

const props = defineProps({
  sn: {
    type: String,
    default: ''
  },
  cookingId: {
    type: String,
    default: ''
  },
  recipeId: {
    type: String,
    default: ''
  }
})

const uToastRef = ref(null)
const deviceStore = useDeviceStore()
const deviceStatus = g_i.device.DeviceStatus
const progressTime = ref(0) // 用来更新设备信息的响应式字段
// 页面参数
const timer = ref(null)
const bgColor = ref(g_style.acticeBgColor)
const bgWidth = ref(0) // 背景色宽度百分比
const stepIndex = ref(0)

// 获取设备列表下的菜谱信息与烹饪信息
const deviceSumInfo = computed(_ => {
  const deviceInfo = g_busTool.getDeviceInfoBySn(props.sn) || {}
  const cookingInfo = g_busTool.getCookingInfoById(props.cookingId) || {}
  const recipeInfo = g_busTool.getRecipeInfoById(props.recipeId) || {}
  // 对菜谱的步骤时长进行数字化处理
  const newRecipeInfo = g_.cloneDeep(recipeInfo)
  newRecipeInfo.stepList = (newRecipeInfo.stepList || []).map(item => {
    item.timeOffset = item.timeOffset * 1
    return item
  })
  const progressObj = g_busTool.calculateProgress(cookingInfo, newRecipeInfo)
  stepIndex.value = cookingInfo.step - 1
  console.log('菜谱烹饪进度-更新', progressObj)

  return {
    deviceInfo,
    currentWorkTemperatureProgress:
      ((deviceInfo.currentWorkTemperature / 300) * 100).toFixed(0) * 1,
    currentWorkPowerLevelProgress:
      ((deviceInfo.currentWorkPowerLevel / 6) * 100).toFixed(0) * 1,
    cookingInfo,
    recipeInfo: newRecipeInfo,
    progressTime: progressTime.value,
    progress: progressObj.progress,
    remainSecondsText: `${progressObj.remainSeconds}秒`,
    curStepProgress: progressObj.curStepProgress
  }
})

const setStepAni = _ => {
  const { stepList } = deviceSumInfo.value.recipeInfo
  const times = stepList[stepIndex.value].timeOffset
  const stepLength = 100 / ((times * 1000) / 150)
  bgWidth.value = 0
  clearInterval(timer.value)
  timer.value = setInterval(_ => {
    // console.log('步骤模拟运行中...')
    bgWidth.value += stepLength
    if (bgWidth.value >= 100) {
      clearInterval(timer.value)
    }
  }, 150)
}

watch(
  () => deviceSumInfo.value,
  (nv, ov) => {
    console.log('deviceSumInfo.value 值变化:', nv, ov)
    if (
      nv.cookingInfo.step > 0 &&
      nv.curStepProgress < 100 &&
      nv.deviceInfo.status == deviceStatus.Cooking
    ) {
      setTimeout(() => {
        progressTime.value += 1
      }, 1000)
    }
  },
  {
    immediate: true,
    deep: true
  }
)

watch(
  () => stepIndex.value,
  (nv, ov) => {
    console.log('stepIndex.value 值变化:', nv, ov)
    if (nv >= 0 && nv < deviceSumInfo.value.recipeInfo.stepList.length - 1) {
      setStepAni()
    }
  },
  {
    immediate: true,
    deep: true
  }
)

onMounted(_ => {
  console.log('deviceSumInfo.value', deviceSumInfo.value)
})

onBeforeUnmount(_ => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
})

onUnload(() => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
})

const getStepStatusText = i => {
  if (i > stepIndex.value) return '未开始'
  if (i === stepIndex.value) return '进行中'
  return '已完成'
}

const toastTip = (type = 1, message = '操作成功') => {
  // 1-成功 0-失败
  uToastRef.value.show({
    type: type ? 'success' : 'error',
    message,
    duration: 2000
  })
}

// --- 指令发送逻辑 ---
const sendCookCommand = (service, method, params = []) => {
  uni.showLoading({ title: '指令处理中...', mask: true })
  return service[method](props.sn, ...params)
    .then(r => {
      g_utils.writeLog(`${service}-${method}-发送消息成功：`, r)
      toastTip()
      return r
    })
    .catch(e => {
      g_utils.writeLog(`${service}-${method}-发送消息失败：`, e)
      toastTip(0, e)
      throw e
    })
    .finally(() => uni.hideLoading())
}

const handleShutdown = _ => {
  console.log('handleShutdown-关机')
  sendCookCommand(deviceProtocolManualService, 'shutdownDevice').then(() => {
    deviceStore.updateDeviceStatus(props.sn, deviceStatus.Shutdown)
  })
}

const handleAutoWashPot = _ => {
  console.log('handleAutoWashPot-自动洗锅')
  sendCookCommand(deviceProtocolRecipeService, 'startAutoWashPot').then(() => {
    deviceStore.updateDeviceStatus(props.sn, deviceStatus.AutoWashPot)
  })
}

const handleManualWashPot = _ => {
  console.log('handleManualWashPot-手动洗锅')
  sendCookCommand(deviceProtocolManualService, 'startManualWashPot').then(
    () => {
      deviceStore.updateDeviceStatus(props.sn, deviceStatus.ManualWashPot)
    }
  )
}

const handleCompleteWashPot = _ => {
  console.log('handleCompleteWashPot-完成洗锅')
  sendCookCommand(deviceProtocolManualService, 'finishManualWashPot').then(
    () => {
      deviceStore.updateDeviceStatus(props.sn, deviceStatus.Idle)
    }
  )
}

const handlePause = _ => {
  console.log('handlePause-暂停')
  sendCookCommand(deviceProtocolRecipeService, 'pauseCooking').then(() => {
    deviceStore.updateDeviceStatus(props.sn, deviceStatus.Pause)
  })
}

const handleContinue = _ => {
  console.log('handleContinue-继续')
  sendCookCommand(deviceProtocolRecipeService, 'resumeCooking').then(() => {
    deviceStore.updateDeviceStatus(props.sn, deviceStatus.Cooking)
  })
}

const handleStop = _ => {
  console.log('handleStop-终止')
  sendCookCommand(deviceProtocolRecipeService, 'stopCooking').then(() => {
    deviceStore.updateDeviceStatus(props.sn, deviceStatus.WaitPlating)
  })
}

const handleOutPot = _ => {
  console.log('handleOutPot-开始出菜')
  sendCookCommand(deviceProtocolRecipeService, 'startPlating').then(() => {
    deviceStore.updateDeviceStatus(props.sn, deviceStatus.InPlating)
  })
}

const handleCompleteOutPot = _ => {
  console.log('handleCompleteOutPot-完成出菜')
  sendCookCommand(deviceProtocolRecipeService, 'finishPlating').then(() => {
    deviceStore.updateDeviceStatus(props.sn, deviceStatus.Resting)
  })
}
</script>

<style lang="scss" scoped>
.bg-img {
  position: relative;
  width: 100%;
  height: 274rpx;
  .recipe-img {
    width: 100%;
    background-color: rgba(8, 8, 8, 0.36);
  }
}
.recipe-title {
  position: absolute;
  left: 0;
  bottom: 0;
  z-index: 10;
  line-height: 30rpx;
  padding: 16rpx 20rpx;
  font-size: 30rpx;
  font-weight: 400;
  color: var(--color-fff);
}
.content {
  height: calc(100% - 274rpx - 100rpx);
  position: relative;
  z-index: 10;
  padding: 34rpx 20rpx 0;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background-color: #fff;
  border-radius: 34rpx 34rpx 0px 0px;
  .device-title {
    position: relative;
    z-index: 11;
    display: flex;
    justify-content: space-between;
    font-size: 26rpx;
    font-weight: bold;
    color: var(--main-theme);
  }
  .charts-wrap {
    display: flex;
    justify-content: space-around;
    margin-top: 30rpx;
  }
}
.progress-title {
  margin-top: 48rpx;
  font-size: 22rpx;
  font-weight: 600;
  color: var(--color-333);
}
.scroll-content {
  flex: 1;
  position: relative;
  margin-top: 20rpx;
  overflow: hidden;
}
.lists {
  overflow: hidden;
  .list {
    position: relative;
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    &::before {
      position: absolute;
      left: 4.5rpx;
      top: 0;
      z-index: 1;
      display: block;
      content: '';
      width: 1rpx;
      height: calc(100% + 20rpx);
      background-color: #edeeee;
    }
    &:only-child {
      &::before {
        display: none;
      }
    }
    &:first-child {
      &::before {
        top: 50%;
        height: calc(50% + 20rpx);
      }
    }
    &:last-child {
      &::before {
        height: 50%;
      }
    }
    .dot {
      flex-shrink: 0;
      position: relative;
      z-index: 2;
      width: 10rpx;
      height: 10rpx;
      margin-right: 16rpx;
      border-radius: 50%;
      background-color: #d4d6d8;
      &.active {
        background-color: var(--main-theme);
      }
    }
    .step-box {
      width: 100%;
      background-color: var(--sub-theme);
      border-radius: 8rpx;
    }
    .step-content {
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10rpx 24rpx 10rpx 20rpx;
      font-size: 18rpx;
      font-weight: 400;
      color: var(--color-333);
      &.completed {
        color: var(--color-999);
      }
      &.active {
        font-size: 20rpx;
        font-weight: bold;
        color: var(--main-theme);
      }
      &.unactive {
        color: var(--color-333);
      }
      .step {
        //
      }
      .duration {
        padding-left: 10rpx;
      }
    }
  }
}
.btns {
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 10;
  width: 100%;
  padding: 22rpx 39rpx;
  box-sizing: border-box;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: var(--color-fff);
  border-top: 1rpx solid var(--border-color);
  .nw-button-wrap {
    flex: 1;
    margin: 0 25rpx;
  }
  :deep(.nw-button) {
    flex: 1;
    max-width: 300rpx;
    height: 54rpx;
    margin: initial;
    border-radius: 28rpx;
    box-sizing: border-box;
    .u-button__text {
      font-size: 22rpx !important;
      font-weight: 400;
    }
    &:not(.u-button--disabled) .u-button__text {
      color: var(--color-fff);
    }
  }
}
</style>
